<template>
  <TableSearch  :deletSome="deletSome" @addRow="addUser" @deletSome="deletSomeUsers"  :search-fields="searchFields"  @search="handleSearch"  @reset="handleReset"></TableSearch>
  <!-- 表格组件 -->
<!--  <el-card class="form-card">-->
    <TableComponent
        :columns="columns"
        :tableData="tableData"
        :loading="loading"
        @delete="handleDelete"
        :deletSome="deletSome"
        @editRow="editUserRow"
        @somedelete="handleSomeDelete"
    />
<!--  </el-card>-->

</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import TableSearch from '@/components/TableSearch/index.vue';
import TableComponent from '@/components/DataTable/index.vue';

import api from '@/api/role.ts'
import router from "@/router/index.js";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
// 搜索字段
const searchFields = reactive([
  { label: 'roleName', prop: 'roleName', type: 'input' },
]);

// 表格列定义
const columns = [
  { prop: 'roleId', label: 'roleId', width: 120 },
  { prop: 'roleCode', label: 'roleCode', width: 80 },
  { prop: 'roleName', label: 'roleName', width: 180 },
];
const search=ref({
  roleName:''
})
const deletSome=false;
// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
let users;

// 加载表格数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      roleName: search.value.roleName
      // 可以添加其他查询参数
    };
    const response = await api.select(params);
    console.log('response:',response);
    tableData.value = response || [];
    // total.value = response.total || 0;
  } catch (error) {
    console.error('加载数据失败:', error);
    // 友好的错误提示
    ElMessage.error({
      message: error.message || '加载数据失败，请稍后重试',
      duration: 3000
    });

    // 重置数据防止显示旧数据
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};
function addUser() {
  router.push(`/role/edit`);
}
// 批量删除
async function deletSomeUsers() {
  try {
    // 确认对话框
    const confirmResult = await ElMessageBox.confirm(
        '确定要批量删除这些用户吗？此操作不可撤销！',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    if (confirmResult !== 'confirm') {
      return; // 用户点击了取消
    }

    // 极速模式：所有删除请求同时发起
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在批量删除用户...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    const results = await Promise.allSettled(
        Object.values(users).map(user =>
            api.deletUser({ userId: user.userId })
                .then(() => ({ status: 'fulfilled', userId: user.userId }))
                .catch(error => ({ status: 'rejected', userId: user.userId, error }))
        )
    );

    // 关闭加载动画
    loadingInstance.close();

    // 生成统计报告
    const successCount = results.filter(r => r.status === 'fulfilled').length;
    const failedCount = results.filter(r => r.status === 'rejected').length;

    // 刷新数据
    await loadData();

    // 显示操作结果
    if (failedCount === 0) {
      ElMessage.success(`成功删除 ${successCount} 个用户`);
    } else if (successCount === 0) {
      ElMessage.error(`删除失败，所有 ${failedCount} 个用户均未删除成功`);
    } else {
      ElMessage.warning(
          `删除完成，成功 ${successCount} 个，失败 ${failedCount} 个`,
          { duration: 5000 }
      );
    }

    return {
      total: results.length,
      success: successCount,
      failed: failedCount,
      errors: results.filter(r => r.status === 'rejected').map(r => ({
        userId: r.userId,
        error: r.error.message
      }))
    };

  } catch (error) {
    // 用户可能点击了取消按钮，不需要处理
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error(`删除操作出错: ${error.message}`);
    }
    return null;
  }
}

function editUserRow(row) {
  router.push(`/role/${row.roleId}/edit`);
  sessionStorage.setItem("role",JSON.stringify(row));
}
// 处理搜索
const handleSearch = (params) => {
  search.value=params;
  console.log('Search params:', params,search.value);
  currentPage.value = 1;
  loadData();
};

// 处理重置
const handleReset = () => {
  currentPage.value = 1;
  loadData();
};

// 删除功能
const handleDelete = async (row) => {
  // 极速模式：所有删除请求同时发起
  try {
    await ElMessageBox.confirm(
        `确定要删除该角色 "${row.roleId}" (ID: ${row.roleName}) 吗？`,
        '删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false, // 防止误点
          beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              try {
                const loadingInstance = ElLoading.service({
                  lock: true,
                  text: '正在删除该角色...',
                  background: 'rgba(0, 0, 0, 0.7)'
                });


                await api.delete({ roleId: row.roleId });
                done();
                // 关闭加载动画
                loadingInstance.close();
              } catch (error) {
                instance.confirmButtonLoading = false;
                // 关闭加载动画
                loadingInstance.close();
                throw error;
              }
            } else {
              done();
            }
          }
        }
    );

    // 删除成功后刷新数据
    await loadData();

    ElMessage({
      type: 'success',
      message: `用户 "${row.userName}" 删除成功`,
      duration: 3000
    });

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: `删除失败: ${error.message || '未知错误'}`,
        duration: 5000
      });
    } else {
      ElMessage({
        type: 'info',
        message: '已取消删除操作',
        duration: 2000
      });
    }
  }
};

function handleSomeDelete(rows) {
  users=rows;
  console.log(rows,"获取多列的值")
}
// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  loadData();
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadData();
};
function deleteclick() {

}
// 初始化加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
#app {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  min-height: 100vh;
}
</style>
